package com.example.administrator.netdemo.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.cyw.baselibrary.R;
import com.cyw.baselibrary.utils.ToastUtils;
import com.cyw.baselibrary.view.varyview.LoadViewHelper;
import com.cyw.baselibrary.view.varyview.VaryViewHelper;
import com.example.administrator.netdemo.network.RequestHandler;
import com.example.administrator.netdemo.network.RequestModelManager;
import com.example.administrator.netdemo.network.base.ApiService;


/**
 * Created by ChenYuanWang on 2018-01-05.
 */

public abstract class BaseActivity extends Activity {
    public ApiService mApiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(getLayoutId());
        initLoadingHelper();
        mApiService = RequestHandler.getInstance().getApiService(this);
        back();
        initView(savedInstanceState);
    }

    public void showToast(String content) {
        ToastUtils.showShort(this, content);
    }

    public void showToastLong(String content) {
        ToastUtils.showLong(this, content);
    }

    protected abstract int getLayoutId();

    protected abstract void initView(Bundle savedInstanceState);

    public <T extends View> T findView(int viewId) {
        return (T) this.findViewById(viewId);
    }

    public <T extends View> T findView(View view, int viewId) {
        return (T) view.findViewById(viewId);
    }

    protected void back() {
        View header_back_iv = findView(R.id.header_back_iv);
        if (header_back_iv != null) {
            header_back_iv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    hideSoftKeyboard();
                    finish();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelRequest();
    }

    protected void cancelRequest() {
        RequestModelManager.getInstance().cancelAllRequest(this.getClass().getName());
    }

    public void hideSoftKeyboard() {// 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }


    //----------------------以下设置触摸EditText外的区域隐藏软键盘-----------------------
    //是否EditText被touch
    private boolean isEditTextTouch = false;
    //是否需要统一处理软键盘，默认都会点击EditText外区域隐藏软键盘(如有需要可在事件分发里设置为false)
    private boolean isNeedManageSoftInput = true;

    public boolean isNeedManageSoftInput() {
        return isNeedManageSoftInput;
    }

    public void setNeedManageSoftInput(boolean needManageSoftInput) {
        isNeedManageSoftInput = needManageSoftInput;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            ViewGroup vGroup = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
            ViewGroup rootView = (ViewGroup) vGroup.getChildAt(0);
            isEditTextTouch = false;//事件触发时总是认为EditText没有被touch，因为可能上一次被touch
            isEditTextTouch(rootView, ev);
            if (!isEditTextTouch && isNeedManageSoftInput) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null && v != null)
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 遍历当前activity的子view，判断被Touch的是不是EditText
     *
     * @param rootView
     * @param event
     */
    private void isEditTextTouch(ViewGroup rootView, MotionEvent event) {
        for (int i = 0; i < rootView.getChildCount(); i++) {
            View childVg = rootView.getChildAt(i);
            if (childVg instanceof ViewGroup) {
                isEditTextTouch((ViewGroup) childVg, event);
            } else if (childVg instanceof EditText) {
                int[] leftTop = new int[2];
                //获取当前输入框相对于屏幕的位置
                childVg.getLocationOnScreen(leftTop);
                int left = leftTop[0];
                int top = leftTop[1];
                int bottom = top + childVg.getHeight();
                int right = left + childVg.getWidth();
                if (event.getRawX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                    if (childVg.isEnabled()) {//touch的是一个可用的EditText
                        isEditTextTouch = true;
                        break;
                    }
                }
            }
        }
    }


    //--------------------------------以下是界面加载助手相关---------------------------------

    /**
     * 界面加载助手
     */
    private LoadViewHelper loadViewHelper;


    /**
     * 初始化界面加载助手
     */
    public void initLoadingHelper() {
        View content = findView(R.id.view_content);
        if (loadViewHelper == null && content != null) {
            loadViewHelper = new LoadViewHelper(new VaryViewHelper(content));
        }
    }


    /**
     * 显示请求数据为空的界面
     */
    public void showEmptyView(View.OnClickListener listener, String message, String buttonText) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showEmpty(listener, message, buttonText, R.mipmap.load_empty);
    }

    /**
     * 显示出错的界面
     */
    public void showErrorView(String message) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showError(message, R.mipmap.icon_load_error);
    }

    /**
     * 显示出错的界面
     */
    public void showErrorView(View.OnClickListener listener, String message, String buttonText) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showError(listener, message, buttonText, R.mipmap.icon_load_error);
    }

    /**
     * 显示请求数据为空的界面
     */
    public void showEmptyView(View.OnClickListener listener, String message, String buttonText, int imageId) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showEmpty(listener, message, buttonText, imageId);
    }

    /**
     * 显示请求数据为空的界面(没有按钮)
     */
    public void showEmptyViewNoButton(String message) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showEmptyNoButton(message, R.mipmap.load_empty);
    }

    /**
     * 显示请求数据为空的界面(没有按钮)
     */
    public void showEmptyViewNoButton(String message, int imageId) {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showEmptyNoButton(message, imageId);
    }


    /**
     * 显示加载中图标
     */
    public void showLoadingView() {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.showLoading();
    }

    /**
     * 显示加载成功的界面(即展示数据的界面)
     */
    public void showSuccessView() {
        if (loadViewHelper == null) {
            return;
        }
        loadViewHelper.restore();
    }

}
